﻿using Newtonsoft.Json;
using PermissionManager.Model;
using PermissionsManager.Core;
using PermissionsManager.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PermissionsManager.BLL
{
    public class RoleService : BaseService<Role>
    {

        private string connstr = ConfigurationHelper.GetAppSettingeValue("conntStr");

        /// <summary>
        /// 得到角色用户
        /// </summary>
        /// <returns></returns>
        public List<RoleUserCount> GetRoleUser()
        {
            using (var db = new PermissionManagerEntities())
            {
                var userName = from b in db.AdminUserRole
                               join c in db.AdminUser
                               on b.AdminUserId equals c.Id
                               select new
                               {
                                   b.RoleId,
                                   c.Name
                               };
                var result = (from a in db.Role
                              select new RoleUserCount
                              {
                                  Id = a.Id,
                                  Count = (from s in db.AdminUserRole where a.Id == s.RoleId select s.Id).Distinct().Count(),
                                  Name = a.Name,
                                  Remark = a.Remark,
                                  CreateTime = a.CreateTime,
                                  IsEnable = a.IsEnable
                              }).ToList();

                foreach (var item in result)
                {
                    List<string> vs = new List<string>();
                    var adminIds = db.AdminUserRole.Where(a => a.RoleId == item.Id).Select(a => a.AdminUserId).ToList();
                    foreach (var b in adminIds)
                    {
                        vs.Add(db.AdminUser.Where(a => a.Id == b).Select(a => a.Name).First());
                    }
                    item.UserName = string.Join(",", vs);
                }
                return result;
            }
        }

        /// <summary>
        /// 得到角色对应的组
        /// </summary>
        /// <param name="RoleId"></param>
        /// <returns></returns>
        public ModuleRole GetModule(int RoleId)
        {
            using (var db = new PermissionManagerEntities())
            {
                return db.ModuleRole.FirstOrDefault(a => a.RoleId == RoleId);
            }
        }

        /// <summary>
        /// 角色更改
        /// </summary>
        /// <param name="role"></param>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public bool UpdateRole(Role role, int moduleId, List<MenuExtend> menus)
        {
            using (var db = new PermissionManagerEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //改变组
                        ModuleRole module = db.ModuleRole.First(a => a.RoleId == role.Id);
                        module.ModuleId = moduleId;
                        db.SaveChanges();
                        //改变角色
                        Role role1 = db.Role.First(a => a.Id == role.Id);
                        role.CreateTime = role1.CreateTime;
                        role.IsEnable = role1.IsEnable;
                        Update(role);
                        //改变功能
                        foreach (var item in menus)
                        {
                            if (item.IsChecked) //新增
                            {
                                RoleFunctionPermission permission = new RoleFunctionPermission()
                                {
                                    RoleId = role.Id,
                                    MenuId = item.Id,
                                    FunctionId = item.FunId
                                };
                                db.RoleFunctionPermission.Add(permission);
                            }
                            else//删除
                            {
                                RoleFunctionPermission permission = db.RoleFunctionPermission.FirstOrDefault(
                                    a => a.FunctionId == item.FunId && a.MenuId == item.Id && a.RoleId == role.Id);
                                db.RoleFunctionPermission.Remove(permission);
                            }
                            db.SaveChanges();
                        }
                        tran.Commit();
                        return true;
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                        return false;
                      
                    }
                }
            }
            return Update(role);

        }
        public bool UpdateIsEnableById(int RoleId, bool IsEnable)
        {

            using (var db = new PermissionManagerEntities())
            {
                Role role = db.Role.First(a => a.Id == RoleId);
                role.IsEnable = IsEnable;
                return Update(role);
            }
        }
        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="role"></param>
        /// <param name="ModuleId"></param>
        /// <returns></returns>
        public bool AddRole(Role role, int ModuleId, List<MenuFun> menuFuns, int userId)
        {
            using (var db = new PermissionManagerEntities())
            {
                using (var trans = db.Database.BeginTransaction())
                {
                    try
                    {
                        role.CreateTime = DateTime.Now;
                        Add(role);
                        //增加对应组关系
                        ModuleRole moduleRole = new ModuleRole()
                        {
                            RoleId = role.Id,
                            ModuleId = ModuleId,
                            CreateTime = DateTime.Now,
                            CreateUserId = userId
                        };
                        db.Entry(moduleRole).State = EntityState.Added;
                        //循环添加功能权限角色
                        foreach (var item in menuFuns)
                        {
                            foreach (var fun in item.Funs)
                            {
                                //增加对应角色功能权限
                                RoleFunctionPermission roleFunction = new RoleFunctionPermission()
                                {
                                    RoleId = role.Id,
                                    FunctionId = fun.Id,
                                    MenuId = item.MenuId
                                };
                                db.Entry(roleFunction).State = EntityState.Added;
                            }
                        }
                        db.SaveChanges();
                        trans.Commit();
                        return true;
                    }
                    catch (Exception)
                    {
                        trans.Rollback();
                        return false;
                    }
                }
            }
        }
    }
}
